const express = require('express')
// 捕获异常
require("express-async-errors")
const app = express()


// 配置跨域
const cors = require('cors')
app.use(cors())


// 设置静态文件目录
// const path = require('path')
// app.use('/file', express.static(path.join(__dirname, '/file')))


// 配置解析 application/x-www-form-urlencoded 格式的表单数据的中间件
app.use(express.urlencoded({ extended: false }))

// 解析body数据
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))// 当extended为false的时候，键值对中的值为'String'或'Array'形式， 当extended为true的时候，则可为任何数据类型。
app.use(bodyParser.json())

const config = require('./config')  // 导入全局配置文件
const expressJWT = require('express-jwt')  // 导入解析jwt的中间件, 需使用5.3.3版本
// 使用expressJwt解析jwt   .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({
    secret: config.jwtSecretKey
}).unless({
    path: config.noJWTPath
}));

// 在路由之前封装返回结果集,全局中间件
const result = require('./utils/result')
app.use((req, res, next)=>{
    res.success = (data, msg) => res.send(result.ok(data,msg));
    res.fail = (msg, status) => res.send(result.err(msg,status));
    res.page = (data, total, msg) => res.send(result.page(data, total,msg));
    res.sqlErr = (msg, status)=> res.send(result.sqlErr(msg,status));
    next();
})


// 注册路由
const registerRouter = ()=>{
    // 管理员
    const adminRouter = require('./router/adminRouter')
    app.use('/admin', adminRouter);
    // 轮播图
    const swiperRouter = require('./router/swiperRouter')
    app.use('/swiper', swiperRouter);
    // 动态
    const activityRouter = require('./router/activityRouter')
    app.use('/activity', activityRouter);
    // 科研成果
    const researchResultRouter = require('./router/researchResultRouter')
    app.use('/researchResult', researchResultRouter);
    // 研究课题
    const researchTopicRouter = require('./router/researchTopicRouter')
    app.use('/researchTopic', researchTopicRouter);
    // 研究院简介
    const overviewRouter = require('./router/overviewRouter')
    app.use('/overview', overviewRouter);
    // 发展历程
    const courseRouter = require('./router/courseRouter')
    app.use('/course', courseRouter);
    // 对外交流
    const exchangeRouter = require('./router/exchangeRouter')
    app.use('/exchange', exchangeRouter);
    // 联系我们
    const relationRouter = require('./router/relationRouter')
    app.use('/relation', relationRouter);
    // 科研人员
    const researcherRouter = require('./router/researcherRouter')
    app.use('/researcher', researcherRouter);
    // 人才培养
    const talentRouter = require('./router/talentRouter')
    app.use('/talent', talentRouter);
    // 文件
    const fileRouter = require('./router/fileRouter')
    app.use('/file', fileRouter);
    // 搜索
    const searchRouter = require('./router/searchRouter')
    app.use('/search', searchRouter);
}
registerRouter();



// 错误级中间件，必须放在路由之后
const joi = require('joi')
app.use((err, req, res, next) => {
    if (err instanceof joi.ValidationError) return res.send({
        status_message: err.details[0].path[0] + "数据不合法！",
        status: 400
    });
    else if (err.name === 'UnauthorizedError') {
        // TokenExpiredError: jwt expired
        if(err.code=='invalid_token') return res.send({
            status: 402,
            status_message: '登录已过期!'
        });
        else return res.status(401).send({
            status: 401,
            status_message: '请先登录!'
        });
    }
    else {
        console.log("错误------------------------------\n",err)
        res.status(404).send({
            status_message: "找不到",
            status: 404
        })
    }
})





// 启动服务
const service = app.listen(config.port,()=>{
    const port = service.address().port;
    console.log(`service running at http://localhost:${config.port}`);
})
